package com.talent.web.controller;//package com.talent.web.controller;

import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import com.talent.web.datasource.influxdb.InfluxDbDataVo;
import com.talent.web.datasource.influxdb.InfluxDbItem;
import com.talent.web.datasource.influxdb.TlInfluxdbTemplate;
import com.talent.web.model.TalentResult;
import com.talent.web.utils.TlConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Nullable;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

/**
 * @ClassName：InfluxDbController
 * @Author: hszhou
 * @Date: 2024/10/30 9:49
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@RestController
@RequestMapping("influx")
@Slf4j
@RequiredArgsConstructor
public class InfluxDbController {



    private final @Nullable TlInfluxdbTemplate influxdbTemplate;


    @GetMapping("demo")
    public TalentResult<InfluxDbDataVo> demo(){

        InfluxDbDataVo dataVo = new InfluxDbDataVo();
        TreeSet<String> legend=new TreeSet<>();
        TreeSet<String> categories=new TreeSet<>();
        List<InfluxDbItem> series=new ArrayList<>();

        String fluxSql = "from(bucket: \"charge\")\n" +
                "  |> range(start: -1m)\n" +
                "  |> filter(fn: (r) => r[\"_measurement\"] == \"charge\")\n" +
                "  |> filter(fn: (r) => r[\"_field\"] == \"boxTemperature\" or r[\"_field\"] == \"inputCurrent\" or r[\"_field\"] == \"inputPower\" or r[\"_field\"] == \"inputVoltage\")\n";
        List<FluxTable> fluxTables = influxdbTemplate.queryFluxTable(fluxSql);


        for (FluxTable fluxTable : fluxTables) {
            List<FluxRecord> records = fluxTable.getRecords();

            List<Object> data=new ArrayList<>();
            InfluxDbItem item = new InfluxDbItem();
            for (FluxRecord record : records) {
                  String field = record.getField();
                  legend.add(field);
                  item.setName(field);
                  Instant time = record.getTime();
                 String instantString = time.atOffset(java.time.ZoneOffset.UTC).format(TlConstant.FORMATTER);
                 categories.add(instantString);
                 Object value = record.getValue();
                 data.add(value);
            }
            item.setData(data);
            series.add(item);
        }
        dataVo.setSeries(series);
        dataVo.setCategories(categories);
        dataVo.setLegends(legend);
        return TalentResult.success(dataVo);
    }

}
